<template>
  <view style="display: flex; flex-wrap: wrap;" :key="fileKey">
    <view v-for="(file, idx) in files" :key="file.id" class="u-file-contain">
      <uni-icons v-if="dataStatus !== 'detail'" type="clear" size="30"  class="u-file-clear" @click="onDelete(file, idx)"></uni-icons>
      <image class="u-file-image" :src="file.url" @click="onPreview(file)" />
    </view>
    <view v-if="dataStatus !== 'detail' && files.length < limit"	class="u-file-add" @click="onChooseImg">
      <ut-loading v-if="loading" type="surround" position="absolute" :text="$t('app.contentrefresh')"></ut-loading>
      <uni-icons type="camera-filled" size="30" color="#666"></uni-icons>
    </view>
  </view>
</template>
<script setup>
import { ref } from "vue"
import { clone, isArray } from 'xe-utils'
import { onLoad } from '@dcloudio/uni-app';
import { baseUrl, fileUrl } from "@/sheep/config"
import sheep from "@/sheep"

const props = defineProps({
  data: {
    type: Object,
    default() {
      return {}
    }
  },
  dataStatus: {
    type: String,
    default: "edit"
  },
  field: {
    type: String,
    default: "url"
  },
  limit: {
    type: Number,
    default: 9
  },
  sourceTable: {
    type: String,
    default: ""
  },
  sourceId: {
    type: String,
    default: ""
  },
})

const files = ref([])
const photos = defineModel("photos")
const loading = ref(false)
let uploadable = false

const onChooseImg = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['album','camera'],
    success: res => {
      uploadImg(res)
    },
    fail: (err) => {
      console.log('error', err)
    }
  })
}
const uploadImg = async (file) => {
  const token = uni.getStorageSync('token')
  loading.value = true
  uni.uploadFile({
    url: baseUrl + "/nature-permission/api/nt/file/upload",
    filePath: file.tempFilePaths[0],
    name: 'file',
    header: {
      'Authorization': 'Bearer ' + token.access_token,
    },
    success: (respon) => {
      // console.log("respon ====", respon)
      const res = JSON.parse(respon.data)
      console.log("res ====", res)
      if (res.status === 500) {
        loading.value = false
        return sheep.$helper.toast(res.error)
      }
      const fileExtend = file.tempFiles[0].path.split('.').pop();
      const photo = {
        realpath: res.data.path,
        fileName: file.name || file.tempFiles[0].path.split('/').pop(),
        fileSize: file.tempFiles[0].size,
        fileExtend,
        sourceTable: props.sourceTable,
        sourceId: props.sourceId
      }
      if (isArray(props.data[props.field])) {
        props.data[props.field].push(photo)
      } else if (props.sourceTable) {
        photos.value ? photos.value.push(photo) : photos.value = [photo]
      } else {
        props.data[props.field] = res.data.path
      }
      files.value.push({ id: Date.now(), url: fileUrl + res.data.path })
      console.log(files)
      uploadable = true
      loading.value = false
    },fail: (e) => {
      uploadable = true
      loading.value = false
      console.log(e)
    }
  })
}
const upload = () => {
  return new Promise((reslove) => {
    if (uploadable) {
      // 图片已上传完成
      ajax.post('/nature-wms/api/v1/attachment', photos.value).then(_ => {
        reslove(true)
        uploadable = false
        photos.value = []
      }).catch(_ => {
        reslove(false)
      })
    } else {
      reslove(true)
    }
  })
}
const onPreview = () => {
  const photos = clone(files.value, true)
  uni.previewImage({
    urls: photos.map(m => {
      m.url = m.url
      return m.url
    })
  })
}
const onDelete = (fiel, idx) => {
  files.value?.splice(idx, 1)
  photos.value?.splice(idx, 1)
  if (!isArray(props.data[props.field])) {
    props.data[props.field].splice(idx, 1)
  }
}

onLoad(() => {
  if (!isArray(props.data[props.field]) && props.data[props.field]) {
    files.value.push({ id: Date.now(), url: props.data[props.field] })
  } else if (isArray(props.data[props.field])) {
    props.data[props.field].forEach(item => {
      files.value.push({ id: item.id, url: item.realpath })
    })
  }
})


defineExpose({ upload })

</script>
<style lang="scss" scoped>
	.u-file-contain {
		width: 150rpx;
		height: 150rpx;
		margin: 12rpx;
		border-width: 2rpx;
		border-style: solid;
		border-color: rgb(238, 238, 238);
		border-radius: 6rpx;
		position: relative;
	}
	.u-file-image {
		height: 150rpx;
    width: 150rpx;
		border-width: 2rpx;
		border-style: solid;
		border-color: rgb(238, 238, 238);
		border-radius: 12%;
	}
	.u-file-clear {
		color: #00000080;
		z-index: 999;
		position: absolute;
		right: 0;
		top: 0;
	}
	.u-file-add {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 150rpx;
		height: 150rpx;
		margin: 12rpx;
		border: 1px solid #CCC;
    border-radius: 12%;
		position: relative;
	}
</style>